using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace yeqw.FrameWork
{
    public class DownFileHelper
    {
        public  static bool DownFileFromUrl(string Url, string FileName)
        {
            bool flag = false;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.KeepAlive = true;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    flag = SaveBinaryFile(response, FileName);
                }
                else
                {
                    return flag;
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return flag;
        }

        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool flag = true;
            byte[] buffer = new byte[0x400];
            try
            {
                int num;
                if (System.IO.File.Exists(FileName))
                {
                    System.IO.File.Delete(FileName);
                }
                string directoryName = Path.GetDirectoryName(FileName);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                Stream stream = System.IO.File.Open(FileName, FileMode.Create);
                Stream responseStream = response.GetResponseStream();
                do
                {
                    num = responseStream.Read(buffer, 0, buffer.Length);
                    if (num > 0)
                    {
                        stream.Write(buffer, 0, num);
                    }
                }
                while (num > 0);
                stream.Close();
                responseStream.Close();
            }
            catch
            {
                flag = false;
            }
            return flag;
        }
    }
}
